package com.amado.course32;

/**
 * 如果两个对象调用equals相等，那它们的hashCode方法值必须一样
 * <p>
 * hashCode值一样，他们的equals并不一定相等
 */
public class HashMapTest {
	private String name;
	private Integer age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public int hashCode() {
		int hashCode = 0;
		if (name != null) {
			hashCode += name.hashCode();
		}
		if (age != null) {
			hashCode += age.hashCode();
		}
		return hashCode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj instanceof HashMapTest) {
			HashMapTest test = (HashMapTest) obj;
			if (!this.getName().equals(test.getName())) {
				return false;
			}
			if (!this.getAge().equals(test.getAge())) {
				return false;
			}
			return true;
		}
		return false;
	}

	public HashMapTest(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	public static void main(String[] args) {
		HashMapTest test1 = new HashMapTest("abb", 124);
		HashMapTest test2 = new HashMapTest("abc", 123);
		System.out.println(test1.equals(test2));
		System.out.println(test1.hashCode());
		System.out.println(test2.hashCode());

		HashMapTest test3 = new HashMapTest("ccc", 1234);
		HashMapTest test4 = new HashMapTest("ccc", 1234);
		System.out.println(test3.equals(test4));
		System.out.println(test3.hashCode());
		System.out.println(test4.hashCode());
		//
		System.out.println(new Integer(12).hashCode());
	}
}
